<?php

namespace frontend\modules\shop\models;

use Yii;
use common\models\shop\ShopCart;
use common\models\shop\ShopGoods;
use common\models\shop\ShopProduct;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopOrderDiscount;
use common\logics\DiscountLogic;
use common\helpers\ArrayHelper;
use common\models\shop\ShopGoodsStock;
use common\models\trade\Partner;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class OrderForm extends \common\base\Model {

    /**
     * @var int(11) 下单用户ID
     * @example 1
     * @static 是
     */
    public $user_id;

    /**
     * @var int(11) 收件地址ID
     * @example 1
     * @static 是
     */
    public $address_id;

    /**
     * @var int(11) 折扣ID
     * @example 1
     * @static 是
     */
    public $discounts;

    /**
     * shi
     */
    private $_partner = null;
    private $_buyer = null;

    /**
     * 交易中心统一下单请求参数校验
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'address_id'], 'required'],
            //校验buyer_id
            ['discounts', 'validateDiscounts'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'app_id' => '交易中心分配给商户的应用ID',
            'charset' => '编码格式',
            'version' => '接口版本',
        ];
    }

    /**
     * Validates the buyer_id.
     * 商户需要验证该通知数据中的buyer_id是否为商户系统中创建的订单号
     *
     * @param string $attribute the attribute currently being validated
     */
    public function validateDiscounts($attribute) {
        if (!$this->hasErrors()) {
            
        }
    }

    /**
     * Find Partner by [[appid]]
     *
     * @return \common\models\trade\Partner|null
     */
    protected function getPartner() {
        if ($this->_partner === null) {
            $this->_partner = Partner::findByAppId($this->app_id);
        }
        return $this->_partner;
    }

    /**
     * Find Partner by [[appid]]
     *
     * @return \common\models\trade\Partner|null
     */
    protected function getBuyer() {
        if ($this->_buyer === null) {
            $this->_buyer = \common\models\original\Users::findOne($this->buyer_id);
        }
        return $this->_buyer;
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function save() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
            return false;
        }

        $list = ShopCart::waitBalance($this->user_id);
        if (empty($list)) {
            return false;
        }

        $goodslist = $this->formatList($list);

        $dislogic = new DiscountLogic();
        $dislogic->items = $goodslist;
        $goods = $dislogic->reckon();

        $amount = 0;
        $discount = 0;
        $goodsAttributes = [];
        foreach ($goods as $gid => $ginfo) {
            $_amount = $ginfo['price'] * $ginfo['number'];
            $_discount = $_amount - $ginfo['subtotal'];
            $goodsAttributes[] = [
                'goods_id' => $gid,
                'goods_name' => $ginfo['name'],
                'goods_code' => $ginfo['code'],
                'goods_price' => $ginfo['price'],
                'goods_discount' => $_discount,
                'goods_number' => $ginfo['number'],
            ];
            $amount += $_amount;
            $discount += $_discount;
        }

        //创建交易
        $order = new ShopOrder();
        $order->attributes = [
            'user_id' => $this->user_id,
            'receiver_id' => $this->address_id,
            'amount' => $amount,
            'discount' => $discount,
            'status' => ShopOrder::STATUS_DEFAULT,
        ];
        $order->generateNo();

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$order->save()) {
                throw new Exception('交易创建失败！' . ArrayHelper::toString($order->errors));
            }
            $orderId = $order->id;

            $orderGoods = new ShopOrderGoods();
            foreach ($goodsAttributes as $_attributes) {
                $_model = clone $orderGoods;
                $_model->setAttributes($_attributes);
                $_model->order_id = $orderId;
                if (!$_model->save()) {
                    throw new Exception('交易创建失败！' . ArrayHelper::toString($_model->errors));
                }
                ShopGoodsStock::stock($_model->goods_id);
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        
        return $order;
    }


    public function formatList($list) {
        $data = [];
        foreach ($list as $model) {
            $goods = $model->goods;
            if (!$goods) {
                continue;
            }
            $data[$model->goods_id] = [
                'id' => $model->goods_id,
                'name' => $goods->name,
                'code' => $goods->goods_no,
                'price' => $goods->price,
                'number' => $model->num,
                'discount' => $goods->discount,
                'type_id' => $model->product->type_id,
                'brand_id' => $model->product->brand_id,
                'subtotal' => ($goods->price - $goods->discount) * $model->num,
            ];
        }
        return $data;
    }

}
